﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utilities;
using Casanova.Web;
using Domain.Models;
using Domain.DAL;
using System.Data;

namespace WebApp.RepairingTickets
{
    public partial class RepairCompleted : System.Web.UI.Page
    {
        #region Private Properties

        public long RepairingTicketHistoryID
        {
            get
            {
                if (this.ViewState["RepairingTicketHistoryID"] != null)
                {
                    return Convert.ToInt64(this.ViewState["RepairingTicketHistoryID"]);
                }
                return MyConfig.NullNumber;
            }
            set
            {
                this.ViewState["RepairingTicketHistoryID"] = value.ToString();
            }
        }

        public string CreatedDate
        {
            get
            {
                if (rdpCreatedDate.SelectedDate.HasValue && rdpCreatedDate.SelectedDate.Value != null)
                {
                    return rdpCreatedDate.SelectedDate.Value.ToString(MyConfig.DateFormat);
                }
                return string.Empty;
            }
            set
            {
                try
                {
                    rdpCreatedDate.SelectedDate = DateTime.ParseExact(value, MyConfig.DateFormat, null);
                }
                catch (Exception)
                {
                    rdpCreatedDate.SelectedDate = null;
                }
            }
        }

        public string CreatedDateForRepairCompleted
        {
            get
            {
                if (rdpCreatedDateForRepairCompleted.SelectedDate.HasValue && rdpCreatedDateForRepairCompleted.SelectedDate.Value != null)
                {
                    return rdpCreatedDateForRepairCompleted.SelectedDate.Value.ToString(MyConfig.DateFormat);
                }
                return string.Empty;
            }
            set
            {
                try
                {
                    rdpCreatedDateForRepairCompleted.SelectedDate = DateTime.ParseExact(value, MyConfig.DateFormat, null);
                }
                catch (Exception)
                {
                    rdpCreatedDateForRepairCompleted.SelectedDate = null;
                }
            }
        }

        public string IsEdit
        {
            get
            {
                if (this.ViewState["IsEdit"] != null)
                {
                    return this.ViewState["IsEdit"].ToString();
                }
                return string.Empty;
            }
            set
            {
                this.ViewState["IsEdit"] = value;
            }
        }

        #endregion

        #region Event Handlers

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                (Master as SiteMaster).SelectedTab = "ticketManagement";
                if (!IsPostBack)
                {
                    this.pageTitle.Text = Resources.Strings.TicketManagement + @"\" + Resources.Strings.RepairCompleted;

                    this.hdRepairingTypeIsWarrantyID.Value = GetParameterValue(MyConfig.RepairingTypeIsWarrantyIDCode);
                    GetParam();
                    BindRadComboBoxs();
                    LoadTicket();
                    EnableCost();
                }
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {

                if (this.RepairingTicketHistoryID != MyConfig.NullNumber)
                {
                    //Insert
                    if (string.IsNullOrEmpty(this.IsEdit))
                    {
                        if (InsertNewStatusForTicket())
                        {
                            Utility.ShowMessageBox(this.Page, Resources.Strings.SaveSuccess);
                        }
                        else
                        {
                            Utility.ShowMessageBox(this.Page, Resources.Strings.SaveFail);
                        }
                    }
                    else
                    {
                        {//Update
                            if (UpdateExistsStatusForTicket())
                            {
                                Utility.ShowMessageBox(this.Page, Resources.Strings.UpdateSuccess);
                            }
                            else
                            {
                                Utility.ShowMessageBox(this.Page, Resources.Strings.UpdateFail);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(QueryStringUtility.GetString("preUrl", "~/ReceivingTicket/ReceivingTicketManagement.aspx"));
        }

        #endregion

        #region Private Methods

        private void BindRepairingTypes()
        {
            DataSet ds = new DataSet();
            try
            {
                RepairingTypeDAO daoObject = RepairingTypeDAO.GetInstance();
                RepairingType rt = new RepairingType();

                ds = daoObject.Search(rt);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbRepairingType, ds, "RepairingTypeName", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindProductTypes()
        {
            DataSet ds = new DataSet();
            try
            {
                ProductTypeDAO daoObject = ProductTypeDAO.GetInstance();
                ProductType pt = new ProductType();

                ds = daoObject.Search(pt);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbProductType, ds, "ProductTypeName", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindManufacturers()
        {
            DataSet ds = new DataSet();
            try
            {
                ManufacturerDAO daoObject = ManufacturerDAO.GetInstance();
                Manufacturer m = new Manufacturer();

                ds = daoObject.Search(m);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbManufacturer, ds, "Name", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindReceivingEmployees()
        {
            DataSet ds = new DataSet();
            try
            {
                EmployeeDAO daoObject = EmployeeDAO.GetInstance();
                Employee e = new Employee();

                ds = daoObject.Search(e);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbReceivingEmployee, ds, "Name", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindRepairers()
        {
            DataSet ds = new DataSet();
            try
            {
                EmployeeDAO daoObject = EmployeeDAO.GetInstance();
                Employee e = new Employee();

                ds = daoObject.Search(e);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbRepairer, ds, "Name", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindRadComboBoxs()
        {
            try
            {
                BindRepairingTypes();
                BindProductTypes();
                BindManufacturers();
                BindReceivingEmployees();
                BindRepairers();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void GetParam()
        {
            this.RepairingTicketHistoryID = QueryStringUtility.GetInt64("RepairingTicketHistoryID", MyConfig.NullNumber);
            this.IsEdit = QueryStringUtility.GetString("IsEdit", string.Empty);
        }

        private bool InsertNewStatusForTicket()
        {
            bool result = false;
            try
            {
                if (!CheckValidate())
                {
                    return result;
                }

                Customer c = new Customer();
                c = GetCustomerInfo();

                RepairingTicket rt = new RepairingTicket();
                rt = GetRepairingTicketInfo();

                RepairingTicketHistory rth = new RepairingTicketHistory();
                rth = GetRepairingTicketHistoryInfo();

                string updateReceivedInfo = GetParameterValue(MyConfig.UpdateReceivedInfoCode);

                RepairingTicketDAO rtDAO = RepairingTicketDAO.GetInstance();
                long temp = rtDAO.InsertNewStatusForTicket(c, rt, rth, updateReceivedInfo);

                if (temp != MyConfig.NullNumber)
                {
                    this.RepairingTicketHistoryID = temp;
                    this.IsEdit = "1";
                    result = true;
                }
            }
            catch (Exception)
            {
                result = false;
                throw;
            }
            return result;
        }

        private bool UpdateExistsStatusForTicket()
        {
            bool result = false;

            try
            {
                if (!CheckValidate())
                {
                    return result;
                }

                Customer c = new Customer();
                c = GetCustomerInfo();

                RepairingTicket rt = new RepairingTicket();
                rt = GetRepairingTicketInfo();

                RepairingTicketHistory rth = new RepairingTicketHistory();
                rth = GetRepairingTicketHistoryInfo();

                string updateReceivedInfo = GetParameterValue(MyConfig.UpdateReceivedInfoCode);

                RepairingTicketDAO rtDAO = RepairingTicketDAO.GetInstance();
                result = rtDAO.UpdateExistsStatusForTicket(c, rt, rth, updateReceivedInfo);
            }
            catch (Exception)
            {
                result = false;
                throw;
            }

            return result;
        }

        private Customer GetCustomerInfo()
        {
            Customer c = new Customer();
            c.FullName = txtFullName.Text.Trim();
            c.Address = txtAddress.Text.Trim();
            c.Mobile = txtMobile.Text.Trim();
            return c;
        }

        private RepairingTicket GetRepairingTicketInfo()
        {
            RepairingTicket rt = new RepairingTicket();
            try
            {
                if (!string.IsNullOrEmpty(rcbProductType.SelectedValue))
                {
                    rt.ProductType = Convert.ToInt32(rcbProductType.SelectedValue);
                }
                if (!string.IsNullOrEmpty(rcbManufacturer.SelectedValue))
                {
                    rt.Manufacturer = Convert.ToInt32(rcbManufacturer.SelectedValue);
                }
                rt.Model = txtModel.Text.Trim();
                rt.SerialNumber = txtSerialNumber.Text.Trim();
                rt.ProductDescription = txtProductDescription.Text.Trim();
                rt.CreatedDate = this.CreatedDate;
                if (!string.IsNullOrEmpty(rcbReceivingEmployee.SelectedValue))
                {
                    rt.ReceivingEmployee = Convert.ToInt32(rcbReceivingEmployee.SelectedValue);
                }
                rt.Note = txtNote.Text.Trim();
            }
            catch (Exception)
            {
                rt = null;
                throw;
            }

            return rt;
        }

        private RepairingTicketHistory GetRepairingTicketHistoryInfo()
        {
            RepairingTicketHistory rth = new RepairingTicketHistory();
            try
            {
                rth.ID = this.RepairingTicketHistoryID;

                if (rcbRepairingType.SelectedValue != string.Empty)
                {
                    rth.RepairingType = Convert.ToInt32(rcbRepairingType.SelectedValue);
                }
                rth.CreatedDate = this.CreatedDateForRepairCompleted;
                if (rcbRepairer.SelectedValue != string.Empty)
                {
                    rth.Repairer = Convert.ToInt32(rcbRepairer.SelectedValue);
                }
                //If repairing type is warranty then cost is 0
                if(rcbRepairingType.SelectedValue != hdRepairingTypeIsWarrantyID.Value)
                {
                    if (rntCost.Value.HasValue)
                    {
                        rth.Cost = (decimal)rntCost.Value.Value;
                    }
                }
                rth.Description = txtDescription.Text.Trim();
                rth.Note = txtNoteForRepair.Text.Trim();
                StatusDAO sDAO = StatusDAO.GetInstance();
                if (sDAO != null)
                {
                    Status s = sDAO.GetEndStatus();
                    if (s != null)
                    {
                        rth.Status = s.ID;
                    }
                }
            }
            catch (Exception)
            {
                rth = null;
                throw;
            }

            return rth;
        }

        /// <summary>
        /// Load both for receiving ticket & repairing ticket
        /// </summary>
        private void LoadTicket()
        {
            try
            {
                RepairingTicketHistoryDAO rthDAO = RepairingTicketHistoryDAO.GetInstance();
                RepairingTicketHistory rth = new RepairingTicketHistory();
                rth = rthDAO.Get(this.RepairingTicketHistoryID);

                if (rth != null)
                {
                    RepairingTicketDAO rtDAO = RepairingTicketDAO.GetInstance();
                    RepairingTicket rt = new RepairingTicket();
                    rt = rtDAO.Get(rth.TicketID);

                    if (rt != null)
                    {
                        CustomerDAO cDAO = CustomerDAO.GetInstance();
                        Customer c = new Customer();
                        c = cDAO.Get(rt.CustomerID);

                        if (c != null)
                        {
                            //Customer information
                            txtFullName.Text = c.FullName;
                            txtAddress.Text = c.Address;
                            txtMobile.Text = c.Mobile;

                            //Product information
                            rcbProductType.SelectedValue = rt.ProductType.ToString();
                            rcbManufacturer.SelectedValue = rt.Manufacturer.ToString();
                            txtModel.Text = rt.Model;
                            txtSerialNumber.Text = rt.SerialNumber;
                            txtProductDescription.Text = rt.ProductDescription;
                            txtNote.Text = rt.Note;

                            //Receiving information
                            this.CreatedDate = rt.CreatedDate;
                            rcbReceivingEmployee.SelectedValue = rt.ReceivingEmployee.ToString();

                            //Repairing information
                            rcbRepairingType.SelectedValue = rth.RepairingType.ToString();
                            rcbRepairer.SelectedValue = rth.Repairer.ToString();
                            if (!string.IsNullOrEmpty(this.IsEdit))
                            {
                                this.CreatedDateForRepairCompleted = rth.CreatedDate;
                                this.rntCost.Text = rth.Cost.ToString();
                                this.txtDescription.Text = rth.Description;
                                this.txtNoteForRepair.Text = rth.Note;
                            }
                            else
                            {
                                this.CreatedDateForRepairCompleted = DateTime.Now.ToString(MyConfig.DateFormat);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private bool CheckValidate()
        {
            if (string.IsNullOrEmpty(txtFullName.Text.Trim()))
            {
                return false;
            }
            if (string.IsNullOrEmpty(this.rcbProductType.SelectedValue))
            {
                return false;
            }
            if (string.IsNullOrEmpty(this.rcbRepairingType.SelectedValue))
            {
                return false;
            }
            if (string.IsNullOrEmpty(this.CreatedDateForRepairCompleted))
            {
                return false;
            }
            if (string.IsNullOrEmpty(txtDescription.Text.Trim()))
            {
                return false;
            }

            return true;
        }

        private string GetParameterValue(string code)
        {
            string value = string.Empty;
            try
            {
                Domain.DAL.ParameterDAO pDAO = Domain.DAL.ParameterDAO.GetInstance();
                if (pDAO != null)
                {
                    Domain.Models.Parameter p = new Domain.Models.Parameter();

                    p = pDAO.GetByCode(code);
                    if (p != null && !string.IsNullOrEmpty(p.Value))
                    {
                        value = p.Value;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return value;
        }

        private void EnableCost()
        {
            rntCost.Enabled = rcbRepairingType.SelectedValue != hdRepairingTypeIsWarrantyID.Value;
        }
        #endregion
    }
}